<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/4/9
 * Time: 18:28
 * 阻塞模型
 */
namespace Io\Blocking;

class Worker
{
    // 接收
    public $onReceive = null;
    // 链接
    public $onConnect = null;

    public $onClose   = null;

    public $socket    = null;

    public function __construct($socket_address)
    {
        $this->socket = stream_socket_server($socket_address);
        echo $socket_address.PHP_EOL;
    }

    public function index()
    {
        echo '111';
    }

    // 接收和链接处理事
    public function accept()
    {
        while (true) {
            $client = @stream_socket_accept($this->socket);
            if (is_callable($this->onConnect)) {
                // 执行函数
                ($this->onConnect)($this);
            }
            $buffer = '';
//            while (!feof($client)) {
//                echo fgets($client,1024);
//                // $buffer = $buffer.fread($client, 65535);
//            }
            //fread($client, 65535);
            $data = fread($client, 65535);
            if (is_callable($this->onReceive)) {
                // 执行函数
                ($this->onReceive)($this, $client, $data);
            }

            var_dump($buffer);
            fwrite($client,'server hellow');
            fclose($client);
            var_dump($client);
        }
    }

    public function start()
    {
        // 启动服务
        $this->accept();
    }

    public function send($conn, $data)
    {
        fwrite($conn, $data);
    }
}